package com.cloudcc.mobile.view.dynamic;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.bus.DynamicEventList.SendCommentEvent;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.DeleteCommentEvent;
import com.cloudcc.cloudframe.bus.EventList.DynamicSingleEvent;
import com.cloudcc.cloudframe.bus.EventList.VoteDynamicEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.model.DynamicModel;
import com.cloudcc.cloudframe.model.DynamicModel.Comments;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.adapter.DynamicAdapter;
import com.cloudcc.mobile.adapter.DynamicAdapter.OnItemListener;
import com.cloudcc.mobile.adapter.DynamicCommentAdapter;
import com.cloudcc.mobile.adapter.DynamicCommentAdapter.MyOnItemClickListener;
import com.cloudcc.mobile.entity.MyChatter;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.DynamicControl;
import com.cloudcc.mobile.util.LoadingUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.AtContaxtActivity;
import com.cloudcc.mobile.view.activity.MyWebActivity;
import com.cloudcc.mobile.view.activity.UserInfoActivity;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.IWebView;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy.MonitorParam;
import com.cloudcc.mobile.weight.DialogUtils;
import com.cloudcc.mobile.weight.ListViewForScrollView;
import com.cloudcc.mobile.weight.MyDialogClickListener;

/**
 * 动态 详情 考虑兼容
 * 
 * @author seven
 * 
 */
public class DynamicActivity extends BaseActivity implements
		MyOnItemClickListener, IEventLife, OnItemListener {
	private static final int CHATER_DETAIL_ACTIVITY_AT = 7000;

	public static final String KEY_CHATID = "chatId";
	public static final String KEY_DYNAMIC = "myChatter";

	@Bind(R.id.back)
	ImageView back;
	@Bind(R.id.refresh)
	ImageView ivRefresh;
	@Bind(R.id.listview)
	ListViewForScrollView mDetail;
	@Bind(R.id.listview_c)
	ListViewForScrollView mComments;

	@Bind(R.id.scrollview)
	ScrollView scLayout;
	@Bind(R.id.dynamic_detail_bottomline)
	View  bottomLine;

	@Bind(R.id.ed_comment)
	EditText etCommentContent;

	private DynamicModel dynamicModel;

	private DynamicCommentAdapter commentAdapter;
	private DynamicAdapter dynamicAdapter;

	private DynamicControl dynamicPresenter = new DynamicControl();

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		register();
		dynamicModel =new DynamicModel();
		MyChatter myChatter = (MyChatter) getIntent().getSerializableExtra(
				KEY_DYNAMIC);
		if (myChatter != null) {
			dynamicModel = GsonUtil.covertBean(myChatter, DynamicModel.class);
			ArrayList<DynamicModel> arrayList = new ArrayList<DynamicModel>();
			arrayList.add(dynamicModel);
			fillDynamic(arrayList);
		}
		String dynamicId = getIntent().getStringExtra(KEY_CHATID);
		if (dynamicId != null) {
			dynamicModel.id=dynamicId;
		}
		refreshData(dynamicModel.id);
		initReceiver();
	}

	private void fillDynamic(List<DynamicModel> data) {
		dynamicModel = data.get(0);
		if (dynamicAdapter == null) {
			dynamicAdapter = new DynamicAdapter(mContext);
			dynamicAdapter.setOnItemtListener(this);
			mDetail.setAdapter(dynamicAdapter);
	}
		dynamicAdapter.changeData(data);
		setListViewHeightBasedOnChildren(mContext, mDetail);
		
		fillComment(dynamicModel.comments);
	}

	private void fillComment(List<Comments> comments) {
		if (ListUtils.isEmpty(comments)) {
			bottomLine.setVisibility(View.INVISIBLE);
			return;
		}
		commentAdapter = new DynamicCommentAdapter(mContext);
		commentAdapter.setMyOnItemClickListener(this);
		commentAdapter.changeData(dynamicModel.comments);
		mComments.setAdapter(commentAdapter);
		scLayout.fullScroll(ScrollView.FOCUS_DOWN);
		bottomLine.setVisibility(View.VISIBLE);
		setListViewHeightBasedOnChildren(mContext, mComments);
	}

	@OnClick(R.id.r_fasong)
	public void clickSend() {

		showWainting("正在发送评论...");
		dynamicPresenter.sendComment(etCommentContent.getText().toString(),dynamicModel.id);
	}

	private void refreshData(String id) {
		ivRefresh.startAnimation(AnimationUtils.loadAnimation(mContext,
				R.anim.rotate_data_refreshing));
		dynamicPresenter.getDynamic(id);
	}

	/**
	 * 发送 评论 结束
	 * 
	 * @param event
	 */
	public void onEventMainThread(SendCommentEvent event) {
		dismissWainting();
		if (event.isError()) {
			Tools.showInfo(mContext, "评论失败");
			return;
		}
		Tools.showInfo(mContext, "评论成功");
		etCommentContent.setText("");
		refreshData(dynamicModel.id);
	}

	/**
	 * 获得
	 * 
	 * @param event
	 */
	public void onEventMainThread(DynamicSingleEvent event) {
		ivRefresh.postDelayed(new Runnable() {
			@Override
			public void run() {
				ivRefresh.clearAnimation();
			}
		}, 150);

		if (event.isError()) {
			return;
		}
		fillDynamic(event.getData().data);
	}

	/**
	 * 删除评论
	 * 
	 * @param event
	 */
	public void onEventMainThread(DeleteCommentEvent event) {
		Tools.showInfo(mContext, event.isOk() ? "删除评论成功" : "删除评论失败");
	}

	@Override
	public void onClickMore(Comments t, int posf) {
		final int pos = posf;
		final String[] items = new String[] { "赞", "删除" };

		boolean isMe = StringUtils.equals(
				UserManager.getManager().getUser().userId, t.authorId);

		// #1 当前是赞了还是没攒
		if (t.ispraised) {// 是我的 我已经攒了
			items[0] = "取消赞";
		}
		if (!isMe) {
			items[1] = "回复";
		}

		Builder builder = new AlertDialog.Builder(mContext);
		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Comments comment = commentAdapter.getItem(pos);
				switch (which) {
				case 0:// 取消 或者 赞
					comment.ispraised = !comment.ispraised;
					commentAdapter.notifyDataSetChanged();
					dynamicPresenter
							.likeComment(comment.id, !comment.ispraised);
					break;
				case 1:// 回复或者删除
					if (StringUtils.equals(items[1], "回复")) {
						String a = "@[" + comment.authorIdname + "]";
						etCommentContent.setText(a);
						etCommentContent.setSelection(a.length());
					} else {
						deleteComment(pos);
					}
					break;
				}
			}
		}).setCancelable(true).show();

	}

	private void deleteComment(final int position) {
		DialogUtils.showWarn(mContext, "删除评论", "确定删除这条回复吗？",
				new MyDialogClickListener() {
					@Override
					public void onClickPositive(Dialog dialog) {
						super.onClickPositive(dialog);
						dialog.cancel();
						Comments comment = commentAdapter.getItem(position);
						dynamicPresenter.deleteComment(comment.id);
						commentAdapter.removeItem(comment);
					}

					@Override
					public void onClickNegative(Dialog dialog) {
						super.onClickNegative(dialog);
						dialog.cancel();
					}
				});
	}

	@OnClick(R.id.r_quan)
	public void clickAiTe() {
		Intent intent = new Intent(mContext, AtContaxtActivity.class);
		startActivityForResult(intent, CHATER_DETAIL_ACTIVITY_AT);
	}

	@OnClick(R.id.refresh)
	public void clickRefresh() {
		refreshData(dynamicModel.id);
	}

	@Override
	public int getLayoutId() {
		return R.layout.dynamic_detail;
	}

	@OnClick(R.id.back)
	public void clickedBack() {
		finish();
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unRegister();
	}

	@Override
	public void onClickLink(DynamicModel t) {
		Intent intent = new Intent(mContext, MyWebActivity.class);
		intent.putExtra(IWebView.KEY_URL, t.linkValue);
		intent.putExtra(IWebView.KEY_NAME,
				StringUtils.isBlank(t.linkName) ? "分享链接" : "分享链接-" + t.linkName);
		mContext.startActivity(intent);
	}

	@Override
	public void onClickUser(DynamicModel t) {
		enterUserInfo(t);
	}

	private void enterUserInfo(DynamicModel t) {
		Intent intent = new Intent(mContext, UserInfoActivity.class);
		intent.putExtra(UserInfoActivity.KEY_USERID,t.authorId);
		startActivity(intent);
	}

	@Override
	public void onClickComment(DynamicModel t) {

	}

	@Override
	public void onClickLike(DynamicModel t, View v) {
		dynamicPresenter.like(t.id, t.ispraised);
	}

	@Override
	public void onClickEventOrTask(DynamicModel t) {
		/*AppContext.urlString = UrlManager.APP_UR + "/"
				+ UrlTools.getTaskOrEventUrl(t.taskIdOrEventId);
		Intent intent = new Intent(mContext, RelevantActivtiy.class);
		intent.putExtra("web", t.taskIdOrEventId);
		intent.putExtra("web.url", AppContext.urlString);
		mContext.startActivity(intent);*/
		Intent intent = new Intent(mContext, CloudWebViewActivity.class);
		intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
				.getTaskOrScheduleDetailUrl(t.taskIdOrEventId));
		MonitorParam monitorParam = new MonitorParam(
				new String[] { "m=delete" }, WebSyncDefaultProxy.STEP_START,
				new String[] { "taskcondition=today", "m=list&objid=task",
						"eventcondition=today" }, true,
				WebSyncDefaultProxy.STEP_START);
		MonitorParam monitorParam2 = new MonitorParam(
				new String[] { "m=save" }, WebSyncDefaultProxy.STEP_START,
				new String[] { "m=query" }, true,
				WebSyncDefaultProxy.STEP_OVERRIDEURL);
		MonitorParam monitorParam3 = new MonitorParam(new String[] {
				"taskcondition=today", "eventcondition=today" },
				WebSyncDefaultProxy.STEP_START, new String[] {
						"taskcondition=today", "eventcondition=today" }, true,
				WebSyncDefaultProxy.STEP_START);
		monitorParam3.isCallBack = false;
		intent.putExtra(
				"callback",
				WebSyncDefaultProxy
						.creatDefaultProxy(
								ReceiverConstant.RECEIVE_REFRESH_SCHEDULE)
						.addMonitorParam(monitorParam)
						.addMonitorParam(monitorParam2)
						.addMonitorParam(monitorParam3).addHomeMonitor());

		startActivity(intent);

	}

	@Override
	public void onClickCollect(DynamicModel t) {

	}

	@Override
	public void onClickDelete(DynamicModel t, int pos) {
		if (StringUtils.equals(t.authorId,
				UserManager.getManager().getUser().userId)) {
			showDialog(t, pos);
		}

	}

	class Ddialog {
		private TextView name;
		private Button cancle, sure;
	}

	protected void showDialog(final DynamicModel t, int pos) {
		final Ddialog dd = new Ddialog();
		LayoutInflater inflater = LayoutInflater.from(mContext);
		View layout = inflater.inflate(R.layout.define_deleted, null);
		dd.name = (TextView) layout.findViewById(R.id.titletitle);
		dd.name.setText("确定删除这条微贴吗？");
		final AlertDialog builder = new AlertDialog.Builder(mContext).create();
		builder.setView(layout);
		builder.show();
		Button cancle = (Button) layout.findViewById(R.id.quxiaocanle);
		cancle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.cancel();
			}
		});
		Button sure = (Button) layout.findViewById(R.id.quedingsure);
		sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dynamicPresenter.delete(t.id);
				dynamicAdapter.removeItem(t);
				builder.cancel();
			}
		});

	}

	@Override
	public void onClickDownload(DynamicModel t, int pos) {
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		LoadingUtils loading = new LoadingUtils(mContext, covertBean, pos);
		loading.loadingFile();

	}

	@Override
	public void onClickRelation(DynamicModel t) {
		AppContext.urlString = UrlManager.getManager().addReturnUrl(UrlManager.getRootUrl()+ UrlTools.getObjectUrl(t.targetId));
		Intent intent = new Intent(mContext, RelevantActivtiy.class);
		intent.putExtra("web", t.targetId);
		intent.putExtra("web.url",UrlManager.getManager().addReturnUrl(UrlManager.getRootUrl()+ UrlTools.getObjectUrl(t.targetId)));
		mContext.startActivity(intent);

	}


	@Override
	public void onClickVote(DynamicModel t, String option) {
		
		showWainting();
		
		dynamicPresenter.sendVote(t.id,option);
	}
	public void onEventMainThread(VoteDynamicEvent event){
		dismissWainting();
		if (event.isError()) {
			return;
		}
		refreshData(dynamicModel.id);
	}
	
	@Override
	public void onClickBody(DynamicModel t) {

	}

	/** 回调 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CHATER_DETAIL_ACTIVITY_AT && resultCode == RESULT_OK) {
			String a = data.getStringExtra("name");
			String[] c = a.split(",");
			for (int i = 0; i < c.length; i++) {
				if (!c[i].equals("")) {
					etCommentContent.append(" @[" + c[i] + "]");
				}
			}
		}
	}

	public static void setListViewHeightBasedOnChildren(Context context,ListView listView) {
		if (listView == null)
			return;
		BaseAdapter listAdapter = (BaseAdapter) listView.getAdapter();
		
		if (listAdapter == null) {
			return;
		}
		listAdapter.notifyDataSetChanged();
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0,0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight;
		params.width =LayoutParams.MATCH_PARENT;
		listView.setLayoutParams(params);
		listView.requestLayout();//664-  1007 =343
		LogUtils.d("app", "高度："+listView+"::"+params.height);
	}
	private SyncReceiver mSyncReceiver;

	private void initReceiver() {
		mSyncReceiver = new SyncReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ReceiverConstant.RECEIVE_REFRESH_SCHEDULE);
		mContext.registerReceiver(mSyncReceiver, filter);
	}

	private class SyncReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			refreshData(dynamicModel.id);
		}
	}
}
